{% extends "base.html" %}

{% block title %}待确认预约 - 乒乓球培训管理系统{% endblock %}

{% block page_title %}待确认预约{% endblock %}

{% block extra_css %}
<style>
    .stats-overview {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 12px;
        padding: 25px;
        margin-bottom: 20px;
    }

    .stat-item {
        text-align: center;
        padding: 15px;
    }

    .stat-number {
        font-size: 2rem;
        font-weight: bold;
        margin-bottom: 5px;
    }

    .stat-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }

    .reservation-card {
        background: white;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 15px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        transition: all 0.2s ease;
        position: relative;
        border-left: 4px solid #ffc107;
    }

    .reservation-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0,0,0,0.15);
    }

    .reservation-card.urgent {
        border-left-color: #dc3545;
        background: linear-gradient(135deg, #fff5f5 0%, #ffffff 100%);
    }

    .reservation-card.today {
        border-left-color: #007bff;
        background: linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%);
    }

    .student-info {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
    }

    .student-avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background: #007bff;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        font-weight: bold;
    }

    .student-details h6 {
        margin: 0 0 5px 0;
        font-weight: 600;
    }

    .student-phone {
        color: #6c757d;
        font-size: 0.9rem;
    }

    .time-info {
        background: #f8f9fa;
        border-radius: 6px;
        padding: 12px;
        margin-bottom: 15px;
    }

    .time-display {
        font-size: 1.1rem;
        font-weight: 600;
        color: #495057;
        margin-bottom: 5px;
    }

    .date-display {
        color: #6c757d;
        font-size: 0.9rem;
    }

    .table-info {
        display: inline-flex;
        align-items: center;
        background: #e3f2fd;
        color: #1976d2;
        padding: 6px 12px;
        border-radius: 15px;
        font-size: 0.85rem;
        margin-bottom: 15px;
    }

    .table-info i {
        margin-right: 5px;
    }

    .apply-note {
        background: #fff3e0;
        border: 1px solid #ffcc02;
        border-radius: 6px;
        padding: 10px;
        margin-bottom: 15px;
        font-size: 0.9rem;
        color: #f57c00;
    }

    .urgency-indicator {
        position: absolute;
        top: 15px;
        right: 15px;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 500;
    }

    .urgency-high {
        background: #ffebee;
        color: #c62828;
        border: 1px solid #ef9a9a;
    }

    .urgency-medium {
        background: #fff3e0;
        color: #f57c00;
        border: 1px solid #ffcc02;
    }

    .urgency-low {
        background: #e8f5e8;
        color: #2e7d32;
        border: 1px solid #81c784;
    }

    .action-buttons {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }

    .btn-confirm {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        border: none;
        color: white;
        transition: all 0.2s ease;
    }

    .btn-confirm:hover {
        background: linear-gradient(135deg, #20c997 0%, #28a745 100%);
        transform: translateY(-1px);
        color: white;
    }

    .btn-reject {
        background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);
        border: none;
        color: white;
        transition: all 0.2s ease;
    }

    .btn-reject:hover {
        background: linear-gradient(135deg, #fd7e14 0%, #dc3545 100%);
        transform: translateY(-1px);
        color: white;
    }

    .filter-section {
        background: white;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .bulk-actions {
        background: #e3f2fd;
        border: 1px solid #bbdefb;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
        display: none;
    }

    .bulk-actions.show {
        display: block;
    }

    .selection-info {
        font-weight: 500;
        color: #1976d2;
        margin-bottom: 10px;
    }

    .reservation-checkbox {
        position: absolute;
        top: 15px;
        left: 15px;
        transform: scale(1.2);
    }

    .reservation-card.selected {
        border-color: #007bff;
        background: linear-gradient(135deg, #e3f2fd 0%, #ffffff 100%);
    }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #6c757d;
    }

    .empty-state i {
        font-size: 4rem;
        margin-bottom: 20px;
        color: #dee2e6;
    }

    .time-until {
        font-size: 0.8rem;
        color: #6c757d;
        margin-top: 5px;
    }

    .quick-stats {
        background: white;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 统计概览 -->
    <div class="stats-overview">
        <div class="row">
            <div class="col-md-3">
                <div class="stat-item">
                    <div class="stat-number">{{ statistics.total_pending }}</div>
                    <div class="stat-label">待确认预约</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-item">
                    <div class="stat-number text-warning">{{ statistics.today_pending }}</div>
                    <div class="stat-label">今日待确认</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-item">
                    <div class="stat-number text-danger">{{ statistics.expired_pending }}</div>
                    <div class="stat-label">超时未处理</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-item">
                    <div class="stat-number" id="todayEarnings">¥0.00</div>
                    <div class="stat-label">今日预计收入</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 快速操作 -->
    <div class="quick-stats">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h5 class="mb-0">
                    <i class="bi bi-clock-history"></i>
                    待确认预约管理
                </h5>
                <small class="text-muted">及时处理学员的预约申请</small>
            </div>
            <div class="col-md-6 text-end">
                <button type="button" class="btn btn-outline-primary me-2" onclick="toggleSelectMode()">
                    <i class="bi bi-check-square"></i> 批量操作
                </button>
                <a href="{{ url_for('coach_reservations.confirmed') }}" class="btn btn-primary">
                    <i class="bi bi-calendar-check"></i> 已确认预约
                </a>
            </div>
        </div>
    </div>

    <!-- 筛选器 -->
    <div class="filter-section">
        <form method="GET" action="{{ url_for('coach_reservations.pending') }}">
            <div class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label">开始日期</label>
                    <input type="date" name="start_date" class="form-control"
                           value="{{ filter_params.start_date }}">
                </div>
                <div class="col-md-3">
                    <label class="form-label">结束日期</label>
                    <input type="date" name="end_date" class="form-control"
                           value="{{ filter_params.end_date }}">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="bi bi-search"></i> 筛选
                    </button>
                </div>
                <div class="col-md-2">
                    <a href="{{ url_for('coach_reservations.pending') }}" class="btn btn-outline-secondary w-100">
                        <i class="bi bi-arrow-clockwise"></i> 重置
                    </a>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-success w-100" onclick="autoRefresh()">
                        <i class="bi bi-arrow-repeat"></i> 自动刷新
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- 批量操作区域 -->
    <div class="bulk-actions" id="bulkActions">
        <div class="selection-info">
            已选择 <span id="selectedCount">0</span> 个预约
        </div>
        <div class="d-flex gap-2">
            <button type="button" class="btn btn-success" onclick="batchConfirm()">
                <i class="bi bi-check-circle"></i> 批量确认
            </button>
            <button type="button" class="btn btn-outline-secondary" onclick="clearSelection()">
                <i class="bi bi-x"></i> 取消选择
            </button>
        </div>
    </div>

    <!-- 预约列表 -->
    <div class="row">
        {% if reservations %}
            {% for reservation in reservations %}
            <div class="col-12">
                <div class="reservation-card {% if reservation.reservation_date == current_date %}today{% endif %} {% if (current_datetime - reservation.created_at).total_seconds() > 86400 %}urgent{% endif %}"
                     data-reservation-id="{{ reservation.id }}">

                    <!-- 选择框（批量操作时显示） -->
                    <input type="checkbox" class="reservation-checkbox" style="display: none;"
                           value="{{ reservation.id }}" onchange="updateSelection()">

                    <!-- 紧急程度指示器 -->
                    {% set hours_since_created = ((current_datetime - reservation.created_at).total_seconds() / 3600) | int %}
                    <div class="urgency-indicator {% if hours_since_created > 24 %}urgency-high{% elif hours_since_created > 12 %}urgency-medium{% else %}urgency-low{% endif %}">
                        {% if hours_since_created > 24 %}
                            超时 {{ hours_since_created }}小时
                        {% elif hours_since_created > 12 %}
                            待处理 {{ hours_since_created }}小时
                        {% else %}
                            新申请
                        {% endif %}
                    </div>

                    <div class="row">
                        <div class="col-md-4">
                            <!-- 学员信息 -->
                            <div class="student-info">
                                <div class="student-avatar">
                                    {{ reservation.student.real_name[0] }}
                                </div>
                                <div class="student-details">
                                    <h6>{{ reservation.student.real_name }}</h6>
                                    <div class="student-phone">
                                        <i class="bi bi-telephone"></i>
                                        {{ reservation.student.phone }}
                                    </div>
                                </div>
                            </div>

                            <!-- 球台信息 -->
                            <div class="table-info">
                                <i class="bi bi-grid-3x3"></i>
                                {{ reservation.table.name }}
                            </div>
                        </div>

                        <div class="col-md-4">
                            <!-- 时间信息 -->
                            <div class="time-info">
                                <div class="time-display">
                                    <i class="bi bi-clock"></i>
                                    {{ reservation.start_time.strftime('%H:%M') }} - {{ reservation.end_time.strftime('%H:%M') }}
                                </div>
                                <div class="date-display">
                                    {{ reservation.reservation_date.strftime('%Y年%m月%d日') }}
                                    ({{ reservation.reservation_date.strftime('%A') }})
                                </div>
                                <div class="time-until">
                                    {% set days_until = (reservation.reservation_date - current_date).days %}
                                    {% if days_until == 0 %}
                                        今天的课程
                                    {% elif days_until == 1 %}
                                        明天的课程
                                    {% elif days_until > 0 %}
                                        {{ days_until }}天后
                                    {% else %}
                                        已过期
                                    {% endif %}
                                </div>
                            </div>

                            <!-- 课程费用 -->
                            <div class="text-muted">
                                <strong>课程费用：</strong>
                                <span class="text-success">¥{{ "%.2f"|format(reservation.get_price_yuan()) }}</span>
                                <small>({{ reservation.duration_minutes }}分钟)</small>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <!-- 申请说明 -->
                            {% if reservation.notes %}
                            <div class="apply-note">
                                <strong>申请说明：</strong><br>
                                {{ reservation.notes }}
                            </div>
                            {% endif %}

                            <!-- 操作按钮 -->
                            <div class="action-buttons">
                                <button type="button" class="btn btn-confirm btn-sm"
                                        onclick="confirmReservation({{ reservation.id }})">
                                    <i class="bi bi-check-circle"></i> 确认
                                </button>
                                <button type="button" class="btn btn-reject btn-sm"
                                        onclick="showRejectModal({{ reservation.id }}, '{{ reservation.student.real_name }}')">
                                    <i class="bi bi-x-circle"></i> 拒绝
                                </button>
                                <a href="{{ url_for('coach_reservations.detail', reservation_id=reservation.id) }}"
                                   class="btn btn-outline-primary btn-sm">
                                    <i class="bi bi-eye"></i> 详情
                                </a>
                                <a href="tel:{{ reservation.student.phone }}" class="btn btn-outline-success btn-sm">
                                    <i class="bi bi-telephone"></i> 联系
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}

            <!-- 分页导航 -->
            {% if pagination and pagination.pages > 1 %}
            <div class="col-12">
                <nav aria-label="分页导航" class="mt-4">
                    <ul class="pagination justify-content-center">
                        {% if pagination.has_prev %}
                        <li class="page-item">
                            <a class="page-link" href="{{ url_for('coach_reservations.pending', page=pagination.prev_num, **filter_params) }}">
                                上一页
                            </a>
                        </li>
                        {% endif %}

                        {% for page_num in pagination.iter_pages() %}
                            {% if page_num %}
                                {% if page_num != pagination.page %}
                                <li class="page-item">
                                    <a class="page-link" href="{{ url_for('coach_reservations.pending', page=page_num, **filter_params) }}">
                                        {{ page_num }}
                                    </a>
                                </li>
                                {% else %}
                                <li class="page-item active">
                                    <span class="page-link">{{ page_num }}</span>
                                </li>
                                {% endif %}
                            {% else %}
                            <li class="page-item disabled">
                                <span class="page-link">...</span>
                            </li>
                            {% endif %}
                        {% endfor %}

                        {% if pagination.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="{{ url_for('coach_reservations.pending', page=pagination.next_num, **filter_params) }}">
                                下一页
                            </a>
                        </li>
                        {% endif %}
                    </ul>
                    <div class="text-center text-muted mt-2">
                        显示第 {{ pagination.per_page * (pagination.page - 1) + 1 }} -
                        {{ pagination.per_page * pagination.page if pagination.page < pagination.pages else pagination.total }} 条，
                        共 {{ pagination.total }} 条记录
                    </div>
                </nav>
            </div>
            {% endif %}

        {% else %}
            <div class="col-12">
                <div class="empty-state">
                    <i class="bi bi-calendar-check"></i>
                    <h5>暂无待确认预约</h5>
                    <p class="text-muted">当前没有需要处理的预约申请</p>
                    <a href="{{ url_for('coach_reservations.confirmed') }}" class="btn btn-primary">
                        <i class="bi bi-calendar3"></i> 查看已确认预约
                    </a>
                </div>
            </div>
        {% endif %}
    </div>
</div>

<!-- 拒绝预约模态框 -->
<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">拒绝预约申请</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="bi bi-exclamation-triangle"></i>
                    您确定要拒绝 <span id="rejectStudentName" class="fw-bold"></span> 的预约申请吗？
                </div>
                <div class="mb-3">
                    <label class="form-label">拒绝原因 <span class="text-danger">*</span></label>
                    <select id="rejectReason" class="form-select" required>
                        <option value="">请选择拒绝原因</option>
                        <option value="时间冲突">时间冲突</option>
                        <option value="个人安排">个人安排</option>
                        <option value="课程已满">课程已满</option>
                        <option value="不适合教学">不适合教学</option>
                        <option value="其他原因">其他原因</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">详细说明</label>
                    <textarea id="rejectDetails" class="form-control" rows="3"
                              placeholder="请详细说明拒绝原因，以便学员理解..."></textarea>
                </div>
                <input type="hidden" id="rejectReservationId">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmReject()">
                    确认拒绝
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let selectMode = false;
let selectedReservations = new Set();
let autoRefreshInterval = null;

// 确认预约
function confirmReservation(reservationId) {
    if (!confirm('确定要确认这个预约吗？')) {
        return;
    }

    fetch(`/coach-reservations/api/confirm/${reservationId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('meta[name=csrf-token]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 移除预约卡片或刷新页面
            const card = document.querySelector(`[data-reservation-id="${reservationId}"]`);
            if (card) {
                card.style.transition = 'all 0.3s ease';
                card.style.opacity = '0';
                card.style.transform = 'translateY(-20px)';
                setTimeout(() => {
                    card.remove();
                }, 300);
            }

            // 显示成功消息
            showToast('success', '预约已确认');

            // 更新统计
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('error', data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('error', '操作失败，请重试');
    });
}

// 显示拒绝模态框
function showRejectModal(reservationId, studentName) {
    document.getElementById('rejectReservationId').value = reservationId;
    document.getElementById('rejectStudentName').textContent = studentName;
    document.getElementById('rejectReason').value = '';
    document.getElementById('rejectDetails').value = '';

    const modal = new bootstrap.Modal(document.getElementById('rejectModal'));
    modal.show();
}

// 确认拒绝
function confirmReject() {
    const reservationId = document.getElementById('rejectReservationId').value;
    const reason = document.getElementById('rejectReason').value;
    const details = document.getElementById('rejectDetails').value;

    if (!reason) {
        alert('请选择拒绝原因');
        return;
    }

    const fullReason = details ? `${reason}：${details}` : reason;

    fetch(`/coach-reservations/api/reject/${reservationId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('meta[name=csrf-token]').getAttribute('content')
        },
        body: JSON.stringify({ reason: fullReason })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 关闭模态框
            bootstrap.Modal.getInstance(document.getElementById('rejectModal')).hide();

            // 移除预约卡片
            const card = document.querySelector(`[data-reservation-id="${reservationId}"]`);
            if (card) {
                card.style.transition = 'all 0.3s ease';
                card.style.opacity = '0';
                card.style.transform = 'translateY(-20px)';
                setTimeout(() => {
                    card.remove();
                }, 300);
            }

            showToast('success', '已拒绝预约');

            // 更新统计
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('error', data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('error', '操作失败，请重试');
    });
}

// 切换选择模式
function toggleSelectMode() {
    selectMode = !selectMode;
    const checkboxes = document.querySelectorAll('.reservation-checkbox');
    const bulkActions = document.getElementById('bulkActions');

    if (selectMode) {
        checkboxes.forEach(cb => cb.style.display = 'block');
        bulkActions.classList.add('show');
    } else {
        checkboxes.forEach(cb => {
            cb.style.display = 'none';
            cb.checked = false;
        });
        bulkActions.classList.remove('show');
        clearSelection();
    }
}

// 更新选择状态
function updateSelection() {
    const checkboxes = document.querySelectorAll('.reservation-checkbox:checked');
    selectedReservations.clear();

    checkboxes.forEach(cb => {
        selectedReservations.add(cb.value);
        cb.closest('.reservation-card').classList.add('selected');
    });

    // 移除未选中的卡片的选中状态
    document.querySelectorAll('.reservation-card').forEach(card => {
        const checkbox = card.querySelector('.reservation-checkbox');
        if (!checkbox.checked) {
            card.classList.remove('selected');
        }
    });

    document.getElementById('selectedCount').textContent = selectedReservations.size;
}

// 清除选择
function clearSelection() {
    selectedReservations.clear();
    document.querySelectorAll('.reservation-checkbox').forEach(cb => {
        cb.checked = false;
    });
    document.querySelectorAll('.reservation-card').forEach(card => {
        card.classList.remove('selected');
    });
    document.getElementById('selectedCount').textContent = '0';
}

// 批量确认
function batchConfirm() {
    if (selectedReservations.size === 0) {
        alert('请先选择要确认的预约');
        return;
    }

    if (!confirm(`确定要批量确认 ${selectedReservations.size} 个预约吗？`)) {
        return;
    }

    const reservationIds = Array.from(selectedReservations);

    fetch('/coach-reservations/api/batch-confirm', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('meta[name=csrf-token]').getAttribute('content')
        },
        body: JSON.stringify({ reservation_ids: reservationIds })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('success', data.message);
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('error', data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('error', '批量操作失败，请重试');
    });
}

// 自动刷新
function autoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
        autoRefreshInterval = null;
        showToast('info', '已停止自动刷新');
    } else {
        autoRefreshInterval = setInterval(() => {
            location.reload();
        }, 30000); // 30秒刷新一次
        showToast('success', '已开启自动刷新（30秒）');
    }
}

// 显示提示消息
function showToast(type, message) {
    // 创建简单的提示框
    const toast = document.createElement('div');
    toast.className = `alert alert-${type === 'success' ? 'success' : type === 'error' ? 'danger' : 'info'} alert-dismissible`;
    toast.style.position = 'fixed';
    toast.style.top = '20px';
    toast.style.right = '20px';
    toast.style.zIndex = '9999';
    toast.innerHTML = `
        ${message}
        <button type="button" class="btn-close" onclick="this.parentElement.remove()"></button>
    `;

    document.body.appendChild(toast);

    // 3秒后自动移除
    setTimeout(() => {
        if (toast.parentElement) {
            toast.remove();
        }
    }, 3000);
}

// 计算今日预计收入
function calculateTodayEarnings() {
    const todayCards = document.querySelectorAll('.reservation-card.today');
    let totalEarnings = 0;

    todayCards.forEach(card => {
        const priceText = card.querySelector('.text-success').textContent;
        const price = parseFloat(priceText.replace('¥', '').replace(',', ''));
        if (!isNaN(price)) {
            totalEarnings += price;
        }
    });

    document.getElementById('todayEarnings').textContent = `¥${totalEarnings.toFixed(2)}`;
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    calculateTodayEarnings();

    // 设置日期筛选的默认值
    const today = new Date().toISOString().split('T')[0];
    const startDateInput = document.querySelector('input[name="start_date"]');
    const endDateInput = document.querySelector('input[name="end_date"]');

    if (startDateInput && !startDateInput.value) {
        startDateInput.value = today;
    }

    if (endDateInput && !endDateInput.value) {
        const nextWeek = new Date();
        nextWeek.setDate(nextWeek.getDate() + 7);
        endDateInput.value = nextWeek.toISOString().split('T')[0];
    }
});

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    if (e.ctrlKey || e.metaKey) {
        switch (e.key) {
            case 'a':
                e.preventDefault();
                toggleSelectMode();
                break;
            case 'r':
                e.preventDefault();
                location.reload();
                break;
        }
    }
});
</script>
{% endblock %}